--
-- DPSView.lua
-- Created by IntelliJ IDEA.
-- User: ema
-- Date: 2018/12/4
-- Time: 17:24
--

local DPSView = MClass("DPSView")
local string_format = string.format

function DPSView:ctor()
    self:setVisible(true)

    self._time = self:findChild("Panel/time")
    self._totalDamage = self:findChild("Panel/time_0")
    self._damagePerSecond = self:findChild("Panel/time_1")
    self._resetButton = self:findChild("Panel/Button")

    self:init()
end

function DPSView:init()
    BattleUIEvent:addEventListener(BattleUIEvent.TYPE.BATTLE_TRAINING_SEND_DAMAGE,handler(self, DPSView.refresh))
    local function _reset(sender, eventType)
        if eventType == ccui.TouchEventType.ended then
            self:resetData()
        end
    end
    self._resetButton:addTouchEventListener(_reset)

    self._lastDamage = 0  --已重置掉的伤害值
    self._damage = 0      --当前伤害值
    self._tick = 0
    self:resetData()

    self._isBegin = true

    local function _tick()
        if not self._isBegin then
            return
        end
        self._tick = self._tick + 1
        self._time:setString(string_format("%ds", self._tick))
        BattleUIEvent:dispatchEvent(BattleUIEvent.TYPE.BATTLE_TRAINING_DAMAGE_REFRESH)
    end
    self._damageScheduler = scheduler.newCron(_tick, 1, true)
end

function DPSView:resetData()
    if not self._canReset then return end
    self._canReset = false
    self._lastDamage = self._lastDamage + self._damage
    self._time:setString("0")
    self._totalDamage:setString("0")
    self._damagePerSecond:setString("0")
    self._tick = 0
end

function DPSView:refresh(data)
    self._canReset = true
    if data then
        for _, v in ipairs(data) do
            if v.rank == 1 then
                self._damage = v.value - self._lastDamage
                self._totalDamage:setString(self._damage)
                if self._tick > 0 then
                    local perDamage = math.floor(self._damage / self._tick)
                    self._damagePerSecond:setString(perDamage)
                end
                break
            end
        end
    end
end

function DPSView:timeStart()
    self._isBegin = true
end

function DPSView:clear()
    if self._damageScheduler then
        scheduler.cancelCron(self._damageScheduler)
        self._damageScheduler = nil
    end
    self:setVisible(false)
end

return DPSView
